package Server;

import java.io.File;
import java.net.URL;
import java.util.Observable;
import java.util.Observer;
import java.util.ResourceBundle;

import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;

public class SongsRueckwaertsController implements Observer{

	@FXML
	private ResourceBundle resources;

	@FXML
	private URL location;

	@FXML
	private Label bluePointsLabel;

	@FXML
	private Label redPointsLabel;

	@FXML
	private Label songNameText;
	@FXML
	private Label teamBuzzerLabel;
	private boolean buzzed = false;
	private MediaPlayer player;
	private NetworkHandler network;
	@FXML
	void initialize() {
		assert bluePointsLabel != null : "fx:id=\"bluePointsLabel\" was not injected: check your FXML file 'zitate.fxml'.";
		assert redPointsLabel != null : "fx:id=\"redPointsLabel\" was not injected: check your FXML file 'zitate.fxml'.";
		assert songNameText != null : "fx:id=\"songNameText\" was not injected: check your FXML file 'zitate.fxml'.";

	}

	public void showSongIntepretAndTitle(String text){
		songNameText.setText(text);
	}
	
	public void clearSongNameField(){
		songNameText.setText("");
		buzzed = false;
		Platform.runLater(new Runnable() {
			
			@Override
			public void run() {
				teamBuzzerLabel.setText("...");
			}
		});
	}
	
	public void incPointsRed(){
		redPointsLabel.setText(String.valueOf(Integer.parseInt(redPointsLabel.getText())+1));
	}
	
	public void incPointsBlue(){
		bluePointsLabel.setText(String.valueOf(Integer.parseInt(bluePointsLabel.getText())+1));
	}
	
	public void playSong(String songURI){
			if(player==null){
				Media song = new Media(songURI);
				player = new MediaPlayer(song);	
			}
			player.play();
		
	}
	
	public void stopSong(){
		if (player != null)
			player.stop();
		player = null;
	}

	public void pauseSong(){
		if(player !=null)
			player.pause();
	}
	
	@Override
	public void update(Observable o, Object arg) {
		String message = (String) arg;
		if(!buzzed){
			buzzed = true;
			try {
				new MediaPlayer(new Media(getClass().getResource("BUZZER.WAV").toURI().toString())).play();
				} catch(Exception e){}
			if(message.contains("red")){
				Platform.runLater(new Runnable() {
					
					@Override
					public void run() {
						teamBuzzerLabel.setText("Rot");
						pauseSong();
					}
				});
			}
			if(message.contains("blue")){
				Platform.runLater(new Runnable() {
					
					@Override
					public void run() {
						teamBuzzerLabel.setText("Blau");
						pauseSong();
					}
				});
			}
		}
			
	}
	
	
	public void setNetwork(NetworkHandler network){
		this.network = network;
		this.network.addObserver(this);
	}
}
